package game;
import game.User;
import java.util.List;
import java.io.BufferedReader;

import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Comparator;


/*文件保存
 * 保存文件
 * 读文件
 */

public class RecordUtil {
				//将分数信息记录在文件中  使用io流将分数记录在文件中
	public static void writeRecord(User user) {
		FileOutputStream out = null ;
                 //1.文件输入流
		try {
		       out = new FileOutputStream("src/score.txt",true);
		         //2.writer方法
		       String record =
		    		   user.getName()+"\t"
		            +user.getScore()+"\t"
		         +user.getLevel()+"\n";
		       out.write(record.getBytes());//字节数组 - 字符串
		       out.flush();
	}
	 catch (Exception e) {
		e.printStackTrace();
	}finally {
		try {
			out.close();
		}catch (IOException e) {
			e.printStackTrace();
		}
	}

 
	
	}

	public static List<User> readRecord() {
		//输入流  包装 Buffered.readLine()
		//读数据 vanse 20 简单
		Reader reader ; 
		BufferedReader br = null;
		List<User> userList = new ArrayList<>();
		try {
		 reader = new FileReader("src/score.txt");
		 br = new BufferedReader(reader) ;
		 //循环读  终止条件
		 String len = null;
		 //存储所有用户的集合  将来需要转换为表格数据
		 while((len= br.readLine()) !=null) {
			User user = parse(len);
			userList.add(user);
		 }
		 userList.sort(new Comparator<User>() {

			@Override
			public int compare(User o1, User o2) {
				return o2.getScore()-o1.getScore();
			}
			 
		 });
		// System.out.println(userList);
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			//只需关闭包装流
			try {
				br.close();
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
		return userList;
	}

	private static User parse(String len) {
       String[] arr =  len.split("\t");//以。。。切割字符串
		return new User(arr[0],Integer.parseInt(arr[1]),arr[2]);
	}
	/*public static void main(String[] args) {
		readRecord();
	}*/
	}
